<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Session;

class Comment extends Controller
{
    // 初始化 防止用户未登录就访问页面
    public function _initialize()
    {
        if (!session('nodeList')) {
            return $this->error('您还未登录,请登录',url('admin/index/index'));
        }
    }
    // 笔记评论显示
    public function index()
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        // 评论信息
        $data = $this->getComment();

        return $this->fetch('comment/index',[
            'data' => $data
        ]);
    }

    // 查看回复笔记
    public function response($comment)
    {
        $auth = request()->controller().request()->action();
        $this->judge($auth);

        // 回复的评论
        $data = $this->getResponse($comment);
        return $this->fetch('comment/response',[
            'data' => $data
        ]);
    }


    // 获取要显示的评论信息
    private function getComment()
    {
        $data = Db::field('n.id nid,n.title,c.id,c.comment,c.comment_at,u.nickname')
            ->table(['2B_user_note' => 'n','2B_note_comment' => 'c', '2B_user_info' => 'u'])
            ->where('n.id=c.note_id')
            ->where('c.uid=u.uid')
            ->order('id')
            ->paginate(10);

        return $data;
    }

    // 获取当前评论的回复评论
    private function getResponse($id)
    {
        $data = Db::field('n.id nid,n.title,r.id,r.uname,r.text,r.response_at')
            ->table(['2B_user_note' => 'n','2B_note_comment' => 'c', '2B_comment_response' => 'r'])
            ->where('r.comment_id',$id)
            ->where('r.comment_id=c.id')
            ->where('c.note_id=n.id')
            ->paginate(10);

        return $data;
    }

    /*
     * 判断权限
     */
    public function judge($auth)
    {
        $nodeList = Session::get('nodeList');
        if (empty($nodeList)) {
            return $this->error('您的权限不足!');
        }
        if (!in_array($auth,$nodeList)) {
            return $this->error('您的权限不足!');
        }
    }
}
